package com.web;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.api.PayMchAPI;
import com.bean.BaseController;
import com.bean.Cons;
import com.bean.PaymentVo;
import com.bean.UnifiedorderResult;
import com.bean.WeixinUser;
import com.utils.PayUtil;
import com.utils.SignUtils;
import com.utils.SignatureUtil;
import com.utils.SysConf;
import com.utils.XmlUtils;

/**
 * Created by qiao on 2017/5/15.
 */
@Controller
@RequestMapping("jianpay")
public class PaymentController extends BaseController {
    private static DecimalFormat df = new DecimalFormat("##0");
    private static BigDecimal Y_100 = new BigDecimal("100");
    private static final Log log = LogFactory.getLog(PaymentController.class);

    @RequestMapping("goto")
    public String gotoPage(String p) {
        return p;
    }

    @RequestMapping("callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("回调");
        try {
            request.setCharacterEncoding(Cons.UTF_8);
            response.setCharacterEncoding(Cons.UTF_8);
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            String resString = XmlUtils.parseRequst(request.getInputStream());
            log.info("通知内容:" + resString);
            Map<String, String> result = new HashMap();
            result.put("return_code", "SUCCESS");
            if (StringUtils.isNotBlank(resString)) {
                Map<String, String> map = XmlUtils.toMap(resString.getBytes(), Cons.UTF_8);
                String res = XmlUtils.toXml(map);
                log.debug("通知消息" + res);
                if (map.containsKey("sign")) {
                    if (!SignUtils.checkParam(map, SysConf.get("weixin.payKey"))) {
                        log.info("回调签名失败");
                        result.put("return_code", "FAIL");
                        result.put("return_msg", "签名失败");
                    } else {
                        String resutlStatus = map.get("return_code");
                        if (StringUtils.equals(resutlStatus, "SUCCESS")) {
                            String outTradeNo = map.get("out_trade_no");
//                            Payment payment = paymentService.lock(outTradeNo);
                            //返回回来的总金额,单位分 所以除以100
                            BigDecimal amountFen = new BigDecimal(map.get("total_fee"));
                            BigDecimal amount = amountFen.divide(Y_100);
//                            if (payment.getAmount().compareTo(amount) == 0 && payment.getStatus() == 0) {
//                                result.put("return_code", "SUCCESS");
//                                payment.setStatus(Cons.INT_1);
//                                payment.setCalltime(new Date());
//                                payment.setWxorderno(map.get("transaction_id"));
//                                payment.setBanktype(map.get("bank_type"));
//                                paymentService.update(payment);
//                            }
                        }
                    }
                }
            }
            log.info("回调完成" + result);
            response.getWriter().write(XmlUtils.toXml(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "payment", method = RequestMethod.POST)
    @ResponseBody
    public String payment(HttpServletRequest request, PaymentVo paymentVo) {
        try {
            request.setCharacterEncoding(Cons.UTF_8);
            WeixinUser user = getSessionUser(request);
            BigDecimal payAmount = paymentVo.getAmount();
            String appid = SysConf.get("weixin.appID");
            String secKey = SysConf.get("weixin.payKey");
            String orderNO = PayUtil.getOrderNo();
            Map<String, String> unifiedorder = new TreeMap<String, String>();
            unifiedorder.put("appid", appid);
            unifiedorder.put("mch_id", SysConf.get("weixin.mch_id"));
            unifiedorder.put("nonce_str", UUID.randomUUID().toString().replace("-", "").toUpperCase());
            unifiedorder.put("body", "助力网");
            unifiedorder.put("out_trade_no", orderNO);
            unifiedorder.put("total_fee", df.format(payAmount.multiply(Y_100)));//单位分
            unifiedorder.put("spbill_create_ip", request.getRemoteAddr());//IP
            unifiedorder.put("notify_url", SysConf.get("weixin.payCallbak"));
            unifiedorder.put("openid", user.getOpenid());
            unifiedorder.put("trade_type", "JSAPI");// 交易类型
            UnifiedorderResult unifiedorderResult = PayMchAPI.payUnifiedorder(unifiedorder, secKey);
            log.info("统一接口调试" + unifiedorderResult.getResult_code());
            String json = PayUtil.generateMchPayJsRequestJson(unifiedorderResult.getPrepay_id(), appid, secKey);
            log.info("微信支付统一接口参数" + json);
            return json;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    @RequestMapping("scanCodeUrl")
    @ResponseBody
    public String scanCodeUrl(String productId) {
        String appId = SysConf.get("weixin.appID");
        String mchid = SysConf.get("weixin.mch_id");
        String timeStamp = System.currentTimeMillis() / 1000 + "";
        String nonceStr = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        Map map = new HashMap();
        map.put("appid", appId);
        map.put("mch_id", mchid);
        map.put("time_stamp", timeStamp);
        map.put("nonce_str", nonceStr);
        map.put("product_id", productId);
        String key = SysConf.get("weixin.payKey");
        String paySign = SignatureUtil.generateSign(map, key);
        String payStr =  "callback({url:'weixin://wxpay/bizpayurl?sign=%s&appid=%s&mch_id=%s&product_id=%s&time_stamp=%s&nonce_str=%s'})";
        return String.format(payStr, paySign, appId, mchid, productId, timeStamp, nonceStr);
    }

    @RequestMapping("scanCode")
    @ResponseBody
    public void scanCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding(Cons.UTF_8);
            response.setCharacterEncoding(Cons.UTF_8);
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            String resString = XmlUtils.parseRequst(request.getInputStream());
            log.info("通知内容:" + resString);
            Map<String, String> map = XmlUtils.toMap(resString.getBytes(), Cons.UTF_8);
            System.out.println("扫码" + map);
            BigDecimal payAmount = new BigDecimal(map.get("product_id"));
            String appid = SysConf.get("weixin.appID");
            String secKey = SysConf.get("weixin.payKey");
            String orderNO = PayUtil.getOrderNo();
            Map<String, String> unifiedorder = new TreeMap<String, String>();
            unifiedorder.put("appid", appid);
            unifiedorder.put("mch_id", SysConf.get("weixin.mch_id"));
            unifiedorder.put("nonce_str", UUID.randomUUID().toString().replace("-", "").toUpperCase());
            unifiedorder.put("body", "助力网");
            unifiedorder.put("out_trade_no", orderNO);
            unifiedorder.put("total_fee", df.format(payAmount.multiply(Y_100)));//单位分
            unifiedorder.put("spbill_create_ip", request.getRemoteAddr());//IP
            unifiedorder.put("notify_url", SysConf.get("weixin.payCallbak"));
            unifiedorder.put("openid", map.get("openid"));
            unifiedorder.put("product_id", map.get("product_id"));// 交易类型
            unifiedorder.put("trade_type", "NATIVE");// 交易类型
            InputStream result = PayMchAPI.payInputStream(unifiedorder, secKey);
            IOUtils.copy(result, response.getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
